// client_hub.go
//
// 功能：连接服务器后，同时启动读/写 goroutine，演示并发写保护。
// 写协程每 2 秒发送一句话；读协程打印广播内容。
package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"os"
	"os/signal"
	"syscall"
	"time"
)

const serverAddr = "127.0.0.1:8000"

func main() {
	conn, err := net.Dial("tcp", serverAddr)
	if err != nil {
		log.Fatalf("dial error: %v", err)
	}
	defer conn.Close()
	log.Printf("[client] connected local=%s remote=%s", conn.LocalAddr(), conn.RemoteAddr())

	// 捕获 Ctrl+C 优雅退出
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	// 写协程：周期发送消息
	go func() {
		ticker := time.NewTicker(2 * time.Second)
		defer ticker.Stop()
		for i := 1; ; i++ {
			select {
			case <-quit:
				return
			case <-ticker.C:
				msg := fmt.Sprintf("message #%d from %s\n", i, conn.LocalAddr())
				if _, err := conn.Write([]byte(msg)); err != nil {
					log.Printf("[client] write error: %v", err)
					return
				}
			}
		}
	}()

	// 读协程：打印服务器广播
	reader := bufio.NewScanner(conn)
	for reader.Scan() {
		log.Printf("[client] recv: %s", reader.Text())
	}
	if err := reader.Err(); err != nil {
		log.Printf("[client] read error: %v", err)
	} else {
		log.Println("[client] server closed connection")
	}
}
